{% load static %}
<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>流量计列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="stylesheet" href="/static/css/font.css">
    <link rel="stylesheet" href="/static/css/xadmin.css">
    <script src="/static/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="/static/js/xadmin.js"></script>
    <script type="text/javascript" src="/static/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="/static/js/jquery.cookie.js"></script>
    <script src="/static/js/flow-meter.js" charset="utf-8"></script>
    <!--[if lt IE 9]>
          <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
          <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
</head>

<body>
<div class="x-nav">
    <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a href="">
            <cite>流量计列表</cite>
        </a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body ">
                    <form class="layui-form layui-col-space5">
                        {% if user.role == 'admin' %}
                            <div class="layui-inline layui-show-xs-block" id="manufacturer_input">
                                <select name="manufacturer_id" lay-search="" id="manufacturer"
                                        lay-filter="manufacturer">
                                    <option value="">供气商</option>
                                </select>
                            </div>
                        {% endif %}
                        {% if user.role == 'admin' or user.role == 'manufacturer' %}
                            <div class="layui-inline layui-show-xs-block" id="dtu_user_input">
                                <select name="dtu_user_id" lay-search="" id="dtu_user" lay-filter="dtu_user">
                                    <option value="">DTU用户</option>
                                </select>
                            </div>
                        {% endif %}
                        <div class="layui-inline layui-show-xs-block">
                            <select name="dtu_id" lay-search="" id="dtu">
                                <option value="">DTU</option>
                            </select>
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <button class="layui-btn" lay-submit="" lay-filter="search">
                                <i class="layui-icon">&#xe615;</i>
                            </button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body ">
                    <table lay-filter="meter" id="meter">
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/html" id="toolbarDemo">
    <button class="layui-btn layui-btn-danger" lay-event="del_batch">
        <i class="layui-icon"></i>批量删除
    </button>
    <button class="layui-btn" onclick="xadmin.open('添加流量计','/meter/add/',700,650)">
        <i class="layui-icon"></i>添加
    </button>
    <button class="layui-btn" lay-event="generate_report">
        生成报表
    </button>
    {% if 'query_meter_data' in user.actions %}
        <button class="layui-btn" lay-event="query_meter">
            查询
        </button>
    {% endif %}
    {% if 'update_valve_state' in user.actions %}
        <button class="layui-btn" lay-event="open_valve">
            开阀
        </button>
        <button class="layui-btn" lay-event="close_valve">
            关阀
        </button>
    {% endif %}
    {% if 'update_recharge_state' in user.actions %}
        <button class="layui-btn" lay-event="open_recharge">
            打开预充值
        </button>
        <button class="layui-btn" lay-event="close_recharge">
            关闭预充值
        </button>
    {% endif %}
    {% if 'reset_meter' in user.actions %}
        <button class="layui-btn" lay-event="reset_meter" style="margin-right: 20px">
            重启仪表
        </button>
    {% endif %}
    {% if 'recharge_meter' in user.actions %}
        <div class="layui-inline layui-show-xs-block">
            <input type="text" name="query_box" placeholder="" autocomplete="off"
                   class="layui-input" id="money">
        </div>
        <button class="layui-btn" lay-event="recharge_meter">
            充值
        </button>
    {% endif %}
</script>
<script>
    layui.use(['table', 'form', 'jquery', 'element', 'tree'],
        function () {

            $ = layui.jquery;
            table = layui.table;
            form = layui.form;

            window.sessionStorage.setItem('table', table);

            let data_map = {};
            table.render({
                elem: '#meter', //指定原始表格元素选择器（推荐id选择器）
                cols: [[
                    {checkbox: true, width: '5%', field: 'id'},
                    {
                        numbbers: true,
                        width: '5%',
                        title: '序号',
                        templet: function (data) {
                            return data.LAY_INDEX;
                        }
                    },
                    {field: 'dtu_no', title: '心跳包'},
                    {field: 'address', title: '物理地址', edit: 'text',},
                    {field: 'surplus_gas', title: '剩余气量（m³）'},
                    {field: 'total_flow', title: '累计用量（m³）'},
                    {field: 'surplus_gas_limits', title: '气量限值（m³）', edit: 'text',},
                    {field: 'flow_rate', title: '瞬时流量（Nm³/h）'},
                    {field: 'flow_ratio', title: '流量系数', edit: 'number',},
                    {field: 'power', title: '电池电压（V）'},
                    {field: 'last_update_time', title: '更新时间', width: '10%'},
                    {field: 'remark', edit: 'text', title: '备注', width: '15%'},
                    {
                        field: 'state',
                        title: '仪表状态',
                        width: '5%',
                        templet: function (d) {
                            return "<button class=\"layui-btn\" onclick=\"xadmin." +
                                "open('仪表状态','/meter/state/?meter_id=" + d['id'] + "',500, 720)\">查看</button>";
                        }
                    },
                ]],
                url: '/handler/meter/?action=query_meter',
                page: true,
                toolbar: '#toolbarDemo',
                defaultToolbar: [],

                done: function (res, curr, count) {

                    data_map = {};
                    for (let i = 0; i < res.data.length; i++) {
                        data_map[res.data[i]['id']] = JSON.parse(JSON.stringify(res.data[i]));
                    }
                }
            });
            //监听单元格编辑
            table.on('edit(meter)',
                function (obj) {
                    let data = {
                        "id": parseInt(obj.data['id']),
                        "address": parseInt(obj.data['address']),
                        "dtu_no": parseInt(obj.data['dtu_no']),
                    };

                    let now_data = JSON.parse(JSON.stringify(data));
                    now_data['remark'] = obj.data['remark'];
                    now_data['surplus_gas_limits'] = parseFloat(obj.data['surplus_gas_limits']);
                    post({
                        "param": JSON.stringify(now_data),
                        "action": "update_meter"
                    }, '/handler/meter/', function (data) {
                        if (!data.success) {
                            layer.msg(data.msg, {icon: 5, time: 2000});
                        }
                    });


                    if (data_map[data['id']]['flow_ratio'] !== obj.data['flow_ratio']) {

                        data['flow_ratio'] = obj.data['flow_ratio'];
                        post({
                            "param": JSON.stringify(data),
                            "action": "update_flow_ratio"
                        }, '/handler/meter/', function (data) {
                            if (!data.success) {
                                layer.msg(data.msg, {icon: 5, time: 2000});
                            }
                        });
                    }
                });


            //头工具栏事件
            table.on('toolbar(meter)',
                function (obj) {
                    let checkStatus = table.checkStatus('meter');
                    let ids = [], state_ids = [];
                    for (let i = 0; i < checkStatus.data.length; i++) {
                        ids.push(checkStatus.data[i].id);
                        state_ids.push(checkStatus.data[i].state_id);
                    }
                    switch (obj.event) {
                        case 'del_batch':
                            layer.confirm('确认要删除吗？', function (index) {
                                post({
                                    "param": JSON.stringify({'meter_ids': ids, 'state_ids': state_ids}),
                                    "action": "del_batch_meter"
                                }, '/handler/meter/', function (data) {
                                    if (!data.success) {
                                        layer.msg(data.msg, {icon: 5, time: 1000});
                                    } else {
                                        layer.msg('删除成功!', {icon: 1});
                                        table.reload('meter');
                                    }
                                });
                            });
                            break;
                        case 'generate_report':
                            post({
                                "param": JSON.stringify({'meter_ids': ids}),
                                "action": "generate_report"
                            }, '/handler/meter/', function (res) {
                                if (!res.success) {
                                    layer.msg(res.msg, {icon: 5, time: 3000});
                                } else {
                                    let param = JSON.stringify({
                                        "filename": res.data,
                                    });
                                    let action = 'download_file';
                                    window.open('/handler/file/?param=' + param + '&action=' + action);
                                }
                            });
                            break;
                        case 'query_meter':
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids}),
                                "action": "query_meter_data"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('查询成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'reset_meter':
                            checkStatus = table.checkStatus('meter');
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids}),
                                "action": "reset_meter"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('重启成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'recharge_meter':
                            checkStatus = table.checkStatus('meter');
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids, 'money': $("#money").val()}),
                                "action": "recharge_meter"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('充值成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'open_valve':
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids, 'valve_state': 1}),
                                "action": "update_valve_state"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('开阀成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'close_valve':
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids, 'valve_state': 0}),
                                "action": "update_valve_state"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('关阀成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'open_recharge':
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids, 'recharge_state': 1}),
                                "action": "update_recharge_state"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('开启预充值功能成功!', {icon: 1});
                                }
                            });
                            break;
                        case 'close_recharge':
                            ids = [];
                            for (let i = 0; i < checkStatus.data.length; i++) {
                                ids.push(checkStatus.data[i].id);
                            }
                            post({
                                "param": JSON.stringify({'meter_ids': ids, 'recharge_state': 0}),
                                "action": "update_recharge_state"
                            }, '/handler/meter/', function (data) {
                                if (!data.success) {
                                    layer.msg(data.msg, {icon: 5, time: 1000});
                                } else {
                                    layer.msg('关闭预充值功能成功!', {icon: 1});
                                }
                            });
                            break;
                    }
                });

            //监听提交
            form.on('submit(search)',
                function (data) {
                    table.reload('meter', {
                        "where": {
                            "param": JSON.stringify(data.field),
                        }
                    });
                    return false;
                });

            {% if user.role == 'admin' %}
                get({
                    "param": JSON.stringify({}),
                    "action": "query_manufacturer"
                }, '/handler/manufacturer/', function (res) {
                    if (!res.success) {
                        layer.msg(res.msg, {icon: 5, time: 1000});
                    } else {
                        for (let i = 0; i < res.data.length; i++) {
                            $("#manufacturer").append('<option value="' + res.data[i].id + '">'
                                + res.data[i].name + '(' + res.data[i].phone + ')' + '</option>');
                        }
                        form.render('select');
                    }
                });
            {% endif %}


            form.on('select(manufacturer)', function () {

                let man_id = $("#manufacturer_input").find('.layui-this').attr('lay-value');
                $("#dtu_user").children().remove();
                $("#dtu_user").append('<option value="">DTU用户</option>');
                form.render('select');
                if (man_id === "") {
                    return;
                }
                get({
                    "param": JSON.stringify({'man_id': man_id}),
                    "action": "query_dtu_user_by_man_id"
                }, '/handler/user/', function (res) {
                    if (!res.success) {
                        layer.msg(res.msg, {icon: 5, time: 1000});
                    } else {

                        for (let i = 0; i < res.data.length; i++) {
                            $("#dtu_user").append('<option value="' + res.data[i].id + '">'
                                + res.data[i].name + '(' + res.data[i].phone + ')' + '</option>');
                        }
                        form.render('select');
                    }
                });

            });
            {% if user.role == 'manufacturer' %}
                get({
                    "param": JSON.stringify({}),
                    "action": "query_dtu_user_of_select_box"
                }, '/handler/user/', function (res) {
                    if (!res.success) {
                        layer.msg(res.msg, {icon: 5, time: 1000});
                    } else {

                        for (let i = 0; i < res.data.length; i++) {
                            $("#dtu_user").append('<option value="' + res.data[i].id + '">'
                                + res.data[i].name + '(' + res.data[i].phone + ')' + '</option>');
                        }
                        form.render('select');
                    }
                });
            {% endif %}


            form.on('select(dtu_user)', function () {

                let user_id = $("#dtu_user").val();

                $("#dtu").children().remove();
                $("#dtu").append('<option value="">DTU</option>');
                form.render('select');
                if (user_id === "") {
                    return;
                }

                get({
                    "param": JSON.stringify({'user_id': user_id}),
                    "action": "query_dtu_by_user_id"
                }, '/handler/user/', function (res) {
                    if (!res.success) {
                        layer.msg(res.msg, {icon: 5, time: 1000});
                    } else {

                        for (let i = 0; i < res.data.length; i++) {
                            $("#dtu").append('<option value="' + res.data[i].id + '">' + res.data[i]['dtu_no'] + '</option>');
                        }
                        form.render('select');
                    }
                });
            });

            {% if user.role == 'dtu_user' %}
                get({
                    "param": JSON.stringify({'user_id': {}}),
                    "action": "query_dtu_of_select_box"
                }, '/handler/dtu/', function (res) {
                    if (!res.success) {
                        layer.msg(res.msg, {icon: 5, time: 1000});
                    } else {

                        for (let i = 0; i < res.data.length; i++) {
                            $("#dtu").append('<option value="' + res.data[i].id + '">' + res.data[i]['dtu_no'] + '</option>');
                        }
                        form.render('select');
                    }
                });
            {% endif %}

            if ("WebSocket" in window) {

                open_falg = false;


                function connect() {
                    // 打开一个 web socket
                    ws = new WebSocket("ws://" + window.location.host + ":{{ websocket_port }}/websocket/");

                    ws.onopen = function () {
                        // Web Socket 已连接上，使用 send() 方法发送数据
                        ws.send(JSON.stringify({'user_id': 'opr_msg_{{ user.id }}', 'opr_msg': true}));
                        open_falg = true;
                    };

                    ws.onmessage = function (evt) {
                        var msg = evt.data;
                        console.log("收到了来自服务器websocket消息" + msg);
                        var msg_dict = JSON.parse(msg);

                        var status = msg_dict['state'];
                        if (status === "error") {
                            layer.msg(msg_dict['msg'], {icon: 5, time: 3000});
                        }
                        else {
                            if (status === "success") {
                                layer.msg(msg_dict['msg'], {icon: 6, time: 3000});
                                table.reload('meter');
                            }
                        }


                    };

                    ws.onclose = function () {
                        // 关闭 websocket
                        /**
                         layer.alert("网络异常，与远程服务器通信中断！", {icon: 5}, function () {
                    layer.closeAll();
                });**/
                        open_falg = false;
                    };
                }

                connect();

                //定时1分钟检查连接是否关闭，如果关闭则重新开启
                setInterval(function () {
                    if (!open_falg) {
                        connect();
                    }
                }, 10 * 1000);

                //4小时主动关一下连接，避免mysql连接超时
                setInterval(function () {
                    ws.close();
                    open_falg = false;
                }, 4 * 3600 * 1000);

            }

        });
</script>

</html>